var arrImg=[
  {
    "name":"car",
    "url":"images/img_car.png"
  },
  {
    "name":"bg",
    "url":"images/bg_game.png"
  }
];
var ImgJson={};
var gameReady=false;
function loadImage(arrImg){
  var n=0;
  for(var i=0;i<arrImg.length;i++){
    (function(i){
      var image=new Image();
      image.src=arrImg[i].url;
      image.onload=function(){ 
        n++;
        ImgJson[arrImg[i].name]=image;
        if(n==arrImg.length){
          gameReady=true;
        }
      }
    })(i)
  }
}
loadImage(arrImg);

var canvas=$(".canvas")[0];
var gd=canvas.getContext("2d");
var winH=$(window).height();
var winW=$(window).width();

var startDate=null;
var endDate=null;
var timer2=null;
var energyH=$(".Energy_max").height();
var per=null;
var last_dur=1;
canvas.width=winW;
canvas.height=winH;

var car_pos=0.66*winH
var bg_pos=-1.8*winH
var state=1;

var car={
  "w":0.097*winH,
  "h":0.204*winH,
  "x":winW/2-0.097*winH/2,
  "y":winH
}
var bg={
  "w":0.621*winH,
  "h":2.8*winH,
  "x":winW/2-0.621*winH/2,
  "y":-2.8*winH+winH
  // "y":0
}

function DrawStartbg(fn){
    if(fn){
      fn();
    }
    gd.drawImage(
      ImgJson.bg,bg.x,bg.y,bg.w,bg.h
    );
}

function DrawCar(fn){
    if(fn){
      fn();
    }
    gd.drawImage(
      ImgJson.car,car.x,car.y,car.w,car.h
    );
}

setInterval(function(){
  if(gameReady){
    if(state==1){
        DrawStartbg()
        DrawCar(function(){
          car.y*=0.994;
          if(car.y<0.66*winH){
            car.y=0.66*winH
            state=4;
          }
        })
    }
    if(state==2){
        DrawStartbg(function(){
          var a=(1-per)/100;
          // console.log(a)
          bg.y*=(0.99+a);
          if(bg.y>(1-per)*bg_pos){
            last_dur*=0.000001
            bg.y=bg.y+last_dur;
            setTimeout(function(){
              state=3;
            },1000)
          }
        })
        DrawCar()
    }
    if(state==3){

    }
  }
},Math.round(1000/120))

//part1
//汽车进入

//part2
//按充能键车辆运行

//part3
//根据车辆状态做出不同动作


var v=null;
var t=null;
var a=0.1;


$(".button_charge").on("touchstart",function(){
  $(".button_charge2").show();
  startDate=new Date();
  charge();
})

$(".button_charge").on("touchend",function(){
  $(".button_charge2").hide();
  clearInterval(timer2)
  state=2;
  v=Math.sqrt(winH*per/0.8*a*2);
  t=v/a;
  console.log(v,t)
})

function charge(){
  timer2=setInterval(function(){
    endDate=new Date();
    per=(endDate-startDate)/3000;
    if(per<1){
      $(".Energy_max").css({
        "height":energyH*per
      })
    }
  },20)
}